import React, { useMemo, useState, useEffect } from 'react';
import { reload_col, filter_row, loc_str, FindBarBase, useCmd, WaitUmd, utc_8, save_data, useHigh, MainView, Btn,
    Title, Ret, show_opt, obj_str, GridTable, cline, urlTb, is_empty, for_obj, loc } from 'sui';
import { load_supply } from 'stock/base/cmd';
import { get_init } from 'trace/cmd';
import { utc_offset } from 'cache';
import { get_col } from './cmd';

const TraceView = ({ hreturn, title, mod }) => {
    const [map_supply, mapSupply] = useState();
    const [col, setCol] = useState();
    const [main, setMain] = useState();
    const [opt_find, optFind] = useState();
    const umd = useCmd(null, "trace");
    const [high] = useHigh(140, 100);

    useEffect(() => {
        get_init(optFind)
        setMain(null);
        reload_col(null, v => setCol(v), `stock${mod}`);
        load_supply(null, null, mapSupply);
    }, [mod]);

    const filteredRows = useMemo(() => {
        if (is_empty(main) || is_empty(col)) {
            return null;
        }

        const lst = col.map(d => d.key);

        return filter_row(main, lst, umd.filter);
    }, [col, main, umd.filter]);

    const hfind = (value) => {
        const opt = [];
        const utc = utc_offset();

        for_obj(value, (k, v) => {
            if (k === "t_start" || k === "t_end") {
                return;
            }

            if (!v) {
                return;
            }

            if (k === "time") {
                opt.push({ge: "time", v: loc_str(value["t_start"]), utc: utc});
                opt.push({le: "time", v: loc_str(value["t_end"]), utc: utc});
                return;
            }

            opt.push({eq: k, v: v});
        });

        if (is_empty(opt)) {
            alert(loc("l_307"));
            return;
        }

        opt.push({eq: "line", v: cline()});

        umd.startWait();

        const tab = `lg${mod}`;

        urlTb(null, "get",
            {
                n: tab,
                obj: "*",
                opt: {desc: true, and: opt}
            },
            r => {
                const data = r[tab]["data"];
                const utc = utc_offset();

                const ret = [];

                data.forEach(t => {
                    const tmp = t["time"];
                    t["time"] = utc_8(tmp, utc);

                    ret.push(t);
                });

                ret.forEach((d, i) => d["index"] = i + 1);

                setMain(ret);

                umd.endWait();
            },
            e => {
                setMain(null);
                umd.endWait();
            });
    };

    const Right = () => {
        return (
            <div className="inline-flex items-center">
                <Btn hcmd={hExport} className="mr-4">{loc("l_298")}</Btn>
                <Ret hcmd={hreturn}/>
            </div>
        );
    };

    const hclear = () => get_init(optFind);

    const getCtl = () => {
        return {
            ctl: [
                {sn: "time", name: loc("l_308"), ctl: "IkFindDate", start: "t_start", end: "t_end"},
            ]
        };
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_101"), key: 'time', width: 180, frozen: true},
            {name: loc("l_238"), key: 'wsn', width: 70, formatter: (props) => show_opt(obj_str(props.row, "wsn"))},
        ];

        get_col(col, tmp, map_supply);

        return tmp;
    };

    const hExport = () => {
        save_data(main, getCol(), `${loc("l_112")}`, umd);
    };

    const Left = () => <Title mod={title} sub={loc("l_112")}/>;

    return (
        <MainView>
            <FindBarBase left={<Left/>} right={<Right/>} hcmd={hfind} data={getCtl()} hclear={hclear} cur={opt_find} hfilter={umd.setFilter}/>
            <GridTable col={getCol()} row={filteredRows} high={high - 50}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {TraceView};
